package com.ztgf.shopping.service.shop;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ztgf.commodity.models.dto.CommodityComboRelationDTO;
import com.ztgf.commodity.models.dto.CommodityInfoDTO;
import com.ztgf.commodity.models.dto.CommoditySpecificationRelationDTO;
import com.ztgf.commodity.models.service.ICommodityComboRelationService;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.service.ICommoditySpecificationRelationService;
import com.ztgf.order.models.dto.OrderReturnCommodityDTO;
import com.ztgf.order.models.dto.OrderStatusDTO;
import com.ztgf.order.models.service.IOrderReturnCommodityService;
import com.ztgf.order.models.service.IOrderStatusService;
import com.ztgf.shopping.mapper.shop.ShopTipMapper;
import com.ztgf.shopping.models.service.audit.IAuditService;
import com.ztgf.shopping.models.service.shop.IShopTipService;
import com.ztgf.shopping.models.vo.shop.ShopLittleRedDotVO;
import com.ztgf.shopping.models.vo.shop.ShopTipVO;
import com.ztgf.user.models.dto.UserInfoDTO;
import com.ztgf.user.models.service.IUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import static com.ztgf.common.utils.UtilConstants.isNull;

/**
 * @author YUE
 * @create 2020-11-13 10:28
 */
@Slf4j
@DubboService
public class ShopTipService implements IShopTipService {

    @DubboReference
    private IOrderStatusService orderStatusService;

    @Autowired
    private IShopCollectServiceImpl iShopCollect;

    @DubboReference
    private IOrderReturnCommodityService orderReturnCommodityService;

    @DubboReference
    private IAuditService iAuditService;

    @Autowired
    private ShopCategoryRelationServiceImpl shopCategoryRelationService;

    @Autowired
    private ShopQualificationServiceImpl shopQualificationService;

    @Autowired
    private ShopEarnestMoneyServiceImpl shopEarnestMoneyService;

    @Autowired
    private ShopAnnualFeeServiceImpl shopAnnualFeeService;
    @Autowired
    private ShopTipMapper shopTipMapper;
    @DubboReference
    private ICommodityInfoService commodityInfoService;
    @DubboReference
    private ICommoditySpecificationRelationService commoditySpecificationRelationService;
    @DubboReference
    private ICommodityComboRelationService commodityComboRelationService;
    @DubboReference
    private IUserInfoService userInfoService;

    /**
     * 根据店铺id和类型获取个人中心统计信息
     *
     * @param shopId 店铺id
     * @param type   1买家 2卖家
     * @return
     */
    @Override
    public ShopTipVO getShopTipNum(Long shopId, Integer type) {
        //也可用 FutureTask ，但是此业务中使用 实现Runnable 此次业务更加简单
        ShopTipVO shopTipVO = new ShopTipVO();
        CountDownLatch countDownLatch = null;
        if (type == 1) {
            countDownLatch = new CountDownLatch(3);
            ShopMyInfoTip shopMyInfoTip = new ShopMyInfoTip(2, shopTipVO, countDownLatch, shopId, type);//收藏
            new Thread(shopMyInfoTip).start();
        } else {
            countDownLatch = new CountDownLatch(4);
            ShopMyInfoTip shopMyInfoTip1 = new ShopMyInfoTip(4, shopTipVO, countDownLatch, shopId, type);//资质
            new Thread(shopMyInfoTip1).start();
            ShopMyInfoTip shopMyInfoTip2 = new ShopMyInfoTip(5, shopTipVO, countDownLatch, shopId, type);//保证金以及年费
            new Thread(shopMyInfoTip2).start();
        }
        ShopMyInfoTip shopMyInfoTip3 = new ShopMyInfoTip(1, shopTipVO, countDownLatch, shopId, type);//订单未完成
        new Thread(shopMyInfoTip3).start();
        ShopMyInfoTip shopMyInfoTip4 = new ShopMyInfoTip(3, shopTipVO, countDownLatch, shopId, type);//售后
        new Thread(shopMyInfoTip4).start();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return shopTipVO;
    }

    @Override
    public ShopLittleRedDotVO getShopLittleRedDot(Long shopId, Integer type) {
        ShopLittleRedDotVO vo = new ShopLittleRedDotVO();
        vo.setInventoryManagementNum(shopTipMapper.getShopSalesNum(shopId) + shopTipMapper.getShopMealNum(shopId));
        vo.setGoodsRemovedNum(this.getGoodsOfRemoveNum(shopId));
        vo.setGoodsCheckNum(this.getGoodsCheckNum(shopId));
        vo.setUndoneOrderNum(this.getUndoneOrderNum(shopId, type,0)); //普通订单
        vo.setUndoneInquiryOrderNum (this.getUndoneOrderNum(shopId, type,1)); //询价订单
        vo.setNumberOfQualifications(this.getQualificationNum(shopId, type));
        vo.setAbandonContractNum(this.getUserContractNum(shopId, type));
        vo.setInvoiceNum(this.getUserInvoiceNum(shopId, type));
        return vo;
    }

    @Override
    public void updateRedDot(Long shopId, Integer type, Integer flag) {
        switch (flag) {
            case 0:
                this.updateAfterSaleLook(shopId, type);
                break;
            case 1:
                this.updateInventory(shopId);
                break;
            case 2:
                this.updateGoodsLookState(shopId, 1);
                break;
            case 3:
                this.updateGoodsLookState(shopId, 2);
                break;
            case 4:
                this.updateOrderLook(shopId, type);
                break;
            case 5:
                this.updateInvoiceLook(shopId, type);
                break;
            case 6:
                this.updateContactLook(shopId, type);
                break;
            case 7:
                this.updateUserLook (shopId, type);
                break;
            default:
                break;
        }
    }

    private void updateUserLook(Long shopId, Integer type) {
        UserInfoDTO userInfoDTO = new UserInfoDTO ();
            userInfoDTO =  userInfoService.selectByShopId(shopId);
        if (userInfoDTO != null){
            userInfoDTO.setLookType (type);
            userInfoService.updateById (userInfoDTO);
        }

    }

    private class ShopMyInfoTip implements Runnable {
        private Integer selectType;//1未完成订单数量 2店铺收藏数量 3我的售后数量 4资质数量 5保证金以及年费 6未完成询价订单数量
        private ShopTipVO shopTipVO;
        private CountDownLatch countDownLatch;
        private Long shopId;
        private Integer shopType;

        ShopMyInfoTip(Integer selectType, ShopTipVO shopTipVO, CountDownLatch countDownLatch, Long shopId, Integer shopType) {
            this.selectType = selectType;
            this.shopTipVO = shopTipVO;
            this.countDownLatch = countDownLatch;
            this.shopId = shopId;
            this.shopType = shopType;
        }

        @Override
        public void run() {
            try {
                if (selectType == 1) {//未完成订单数量
                    shopTipVO.setUnfinishedOrderNum(orderStatusService.getUnfinishedOrderNum(shopId, shopType)); //普通订单
                    shopTipVO.setUnfinishedInquiryOrderNum (orderStatusService.getUnfinishedInquiryOrderNum(shopId, shopType)); //询价订单
                }
                if (selectType == 2) {//店铺收藏数量
                    shopTipVO.setCollectShopsNum(iShopCollect.getCollectShopCountByShopId(shopId));
                }
                if (selectType == 3) {//我的售后数量
                    shopTipVO.setAfterSaleNum(orderReturnCommodityService.getMyAfterSalesNum(shopId, shopType));
                }
                if (selectType == 4) {//资质数量
                    int allNum = 0;
                    Integer num0 = shopQualificationService.getExpireAudisNumByShopId(shopId, Arrays.asList(0, 1, 2, 3, 4, 5, 6));
                    allNum += num0;
//                    Integer num1 = shopQualificationAuditService.getQualificationInfoByShopId(shopId);
//                    allNum += num1;
//                    int num2 = shopQualificationAuditService.queryBrandList(shopId).size();
                    Integer num1 = iAuditService.getNumByTab(1, shopId);
                    allNum += num1;
                    Integer num2 = iAuditService.getNumByTab(2, shopId);
                    allNum += num2;
//                    List<ShopCategoryRelationVO> shopCategoryRelationVOS = shopCategoryRelationService.queryList(shopId);
//                    for (ShopCategoryRelationVO shopCategoryRelationVO : shopCategoryRelationVOS) {
//                        Long brandId = shopCategoryRelationVO.getBrandId();
//                        Integer categoryAuditNum = iAuditService.getNumByTab(3, shopId);
//                        allNum += categoryAuditNum;
//                    }
                    Integer categoryAuditNum = iAuditService.getNumByTab(3, shopId);
                    allNum += categoryAuditNum;
                    shopTipVO.setCertificationNum(allNum);
                }
                if (selectType == 5) {//保证金以及年费数量
                    int earnestMoneyNum = shopEarnestMoneyService.getByShopId(shopId).getVacancyAmount().compareTo(new BigDecimal(0)) == 1 ? 1 : 0;
                    int shopAnnualFeeNum = shopAnnualFeeService.getByShopId(shopId).getVacancyAmount().compareTo(new BigDecimal(0)) == 1 ? 1 : 0;
                    shopTipVO.setEarnestMoneyAndAnnualFeeNum(earnestMoneyNum + shopAnnualFeeNum);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }
    }

    /**
     * @Description: 获取店铺商品已审核被平台下架数量
     * @Author: chenyu.wang
     * @Params: [shopId]
     * @Date: 2020.12.09 10:34
     */
    private Integer getGoodsOfRemoveNum(Long shopId) {
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId).andNew()
                .eq("audit_status", 1).or().eq("is_platform_shelf", 1)
                .andNew().eq("is_push_look", 0);
        return commodityInfoService.selectCount(wrapper);
    }

    /**
     * @Description: 商品审核中，审核不通过数量
     * @Author: chenyu.wang
     * @Params: [shopId]
     * @Date: 2020.12.09 10:47
     */
    private Integer getGoodsCheckNum(Long shopId) {
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId).eq("audit_status", 2)
                .eq("is_pass_look", 0);
        return commodityInfoService.selectCount(wrapper);
    }

    /**
     * @Description: 获取未完成订单数量
     * @Author: chenyu.wang
     * @Params: [shopId, type:1买家 2卖家]
     * @Date: 2020.12.09 11:02
     */
    private Map<Integer, Integer> getUndoneOrderNum(Long shopId, Integer type, Integer inquiryType ) {
        Map<Integer, Integer> map = new HashMap<>();
        if (type == 1) {
            // 待确认
            Integer a = shopTipMapper.getBuyerOrderStateNum(shopId, 0,inquiryType);
            // 待付款
            Integer b = shopTipMapper.getTheBuyerSPendingPaymentQuantity(shopId,inquiryType);
            // 合同待签定
            Integer c = shopTipMapper.getBuyerOrderStateNum(shopId, 1,inquiryType);
            // 待发货
            Integer d = shopTipMapper.getBuyerOrderStateNum(shopId, 3,inquiryType);
            // 待签收
            Integer e = shopTipMapper.getBuyerOrderStateNum(shopId, 4,inquiryType);
            // 全部数量
            Integer allNum = a + b + c + d + e;
            map.put(0, allNum);
            map.put(1, a);
            map.put(2, b);
            map.put(3, c);
            map.put(4, d);
            map.put(5, e);
        } else {
            // 待确认
            Integer a = shopTipMapper.getSellOrderStateNum(shopId, 0,inquiryType);
            // 待付款
            Integer b = shopTipMapper.getTheSellerSPendingPaymentQuantity(shopId,inquiryType);
            // 合同待签定
            Integer c = shopTipMapper.getSellOrderStateNum(shopId, 1,inquiryType);
            // 待发货
            Integer d = shopTipMapper.getSellOrderStateNum(shopId, 3,inquiryType);
            // 待签收
            Integer e = shopTipMapper.getSellOrderStateNum(shopId, 4,inquiryType);
            // 全部数量
            Integer allNum = a + b + c + d + e;
            map.put(0, allNum);
            map.put(1, a);
            map.put(2, b);
            map.put(3, c);
            map.put(4, d);
            map.put(5, e);
        }
        return map;
    }

    /**
     * @Description: 获取店铺资质数量
     * @Author: chenyu.wang
     * @Params: [shopId, type]
     * @Date: 2020.12.09 14:16
     */
    private Map<Integer, Integer> getQualificationNum(Long shopId, Integer type) {
        // 品牌资质
        Integer num2 = iAuditService.getNumByTab(2, shopId);
        Integer num3 = shopQualificationService.getExpireAudisNumByShopId(shopId, Arrays.asList(3, 4, 5, 6));
//        int num2 = shopQualificationAuditService.queryBrandList(shopId).size();
        // 类目资质
        Integer allNum = iAuditService.getNumByTab(3, shopId);

//        List<ShopCategoryRelationVO> shopCategoryRelationVOS = shopCategoryRelationService.queryList(shopId);
//        for (ShopCategoryRelationVO shopCategoryRelationVO : shopCategoryRelationVOS) {
//            Long brandId = shopCategoryRelationVO.getBrandId();
//            Integer categoryAuditNum = shopCategoryRelationAuditService.getCategoryAuditNum(shopId, brandId);
//            allNum += categoryAuditNum;
//        }
        // 基本资质
        Integer num0 = shopQualificationService.getExpireAudisNumByShopId(shopId, Arrays.asList(0, 1, 2));
        Integer num1 = iAuditService.getNumByTab(1, shopId);
//        Integer num1 = shopQualificationAuditService.getQualificationInfoByShopId(shopId);
        Integer basicQualifications = num0 + num1;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(1, basicQualifications);
        map.put(2, num2 + num3);
        map.put(3, allNum);
        return map;
    }

    /**
     * @Description: 获取用户废弃合同数量
     * @Author: chenyu.wang
     * @Params: [shopId, type:1买家 2卖家]
     * @Date: 2020.12.09 14:35
     */
    private Integer getUserContractNum(Long shopId, Integer type) {
        int num;
        if (type == 1) {
            num = shopTipMapper.getBuyerContractNum(shopId);
        } else {
            num = shopTipMapper.getSellContractNum(shopId);
        }
        return num;
    }

    /**
     * @Description: 获取用户发票数量
     * @Author: chenyu.wang
     * @Params: [shopId, type1买家 2卖家]
     * @Date: 2020.12.09 15:03
     */
    private Map<Integer, Integer> getUserInvoiceNum(Long shopId, Integer type) {
        Map<Integer, Integer> map = new HashMap<>();
        Integer a;
        if (type == 1) {
            // 已开
            a = shopTipMapper.getUserInvoiceNum(1, 1, shopId);
        } else {
            // 已开
            a = shopTipMapper.getUserInvoiceNum(2, 1, shopId);
        }
        map.put(0, a);
        map.put(1, a);
        return map;
    }

    /**
     * @Description: 修改商品库存管理已查看
     * @Author: chenyu.wang
     * @Params: [shopId]
     * @Date: 2020.12.10 11:55
     */
    private void updateInventory(Long shopId) {
        // 查询商品表
        Wrapper<CommodityInfoDTO> wrapperA = new EntityWrapper<>();
        wrapperA.eq("shop_id", shopId).eq("audit_status", 1)
                .eq("status", 0).eq("is_platform_shelf", 0)
                .eq("is_remove", 0).eq("is_platform_remove", 0);
        List<CommodityInfoDTO> listA = commodityInfoService.selectList(wrapperA);
        if (isNull(listA)) {
            return;
        }
        for (CommodityInfoDTO goods : listA) {
            // 查询商品规格
            List<CommoditySpecificationRelationDTO> listB = shopTipMapper.queryGoodsSkuList(goods.getId());
            if (!isNull(listB)) {
                for (CommoditySpecificationRelationDTO dtoA : listB) {
                    CommoditySpecificationRelationDTO updateA = new CommoditySpecificationRelationDTO();
                    updateA.setId(dtoA.getId());
                    updateA.setIsLook(1);
                    commoditySpecificationRelationService.updateById(updateA);
                }
            }
            // 查询商品套餐
            List<CommodityComboRelationDTO> listC = shopTipMapper.queryGoodsComboList(goods.getId());
            if (!isNull(listC)) {
                for (CommodityComboRelationDTO dtoB : listC) {
                    CommodityComboRelationDTO updateB = new CommodityComboRelationDTO();
                    updateB.setId(dtoB.getId());
                    updateB.setIsLook(1);
                    commodityComboRelationService.updateById(updateB);
                }
            }
        }
    }

    /**
     * @Description: 修改售后已查看
     * @Author: chenyu.wang
     * @Params: [shopId, type:1买家，2卖家]
     * @Date: 2020.12.10 14:03
     */
    private void updateAfterSaleLook(Long shopId, Integer type) {
        if (type == 1) {
            // 查询买家未查看的售后
            Wrapper<OrderReturnCommodityDTO> wrapperA = new EntityWrapper<>();
            wrapperA.eq("buyers_shop_id", shopId).eq("is_buyer_look", 0)
                    .in("after_sales_state", Arrays.asList(new Integer[]{1, 2}));
            List<OrderReturnCommodityDTO> listA = orderReturnCommodityService.selectList(wrapperA);
            if (isNull(listA)) {
                return;
            }
            for (OrderReturnCommodityDTO dtoA : listA) {
                OrderReturnCommodityDTO updateA = new OrderReturnCommodityDTO();
                updateA.setId(dtoA.getId());
                updateA.setIsBuyerLook(1);
                orderReturnCommodityService.updateById(updateA);
            }
        } else {
            // 查询卖家未查看售后
            Wrapper<OrderReturnCommodityDTO> wrapperB = new EntityWrapper<>();
            wrapperB.eq("seller_shop_id", shopId).eq("is_seller_look", 0)
                    .in("after_sales_state", Arrays.asList(new Integer[]{1, 2}));
            List<OrderReturnCommodityDTO> listB = orderReturnCommodityService.selectList(wrapperB);
            if (isNull(listB)) {
                return;
            }
            for (OrderReturnCommodityDTO dtoB : listB) {
                OrderReturnCommodityDTO updateB = new OrderReturnCommodityDTO();
                updateB.setId(dtoB.getId());
                updateB.setIsSellerLook(1);
                orderReturnCommodityService.updateById(updateB);
            }
        }
    }

    /**
     * @Description: 更改商品已查看
     * @Author: chenyu.wang
     * @Params: [shopId, flag:1被下架，2审核不通过]
     * @Date: 2020.12.10 14:29
     */
    private void updateGoodsLookState(Long shopId, Integer flag) {
        if (flag == 1) {
            Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id", shopId).eq("audit_status", 1)
                    .andNew().eq("audit_status", 1).or().eq("is_platform_shelf", 1)
                    .andNew().eq("is_push_look", 0);
            log.info("1--------------------查询商品开始------------------");
            List<CommodityInfoDTO> listA = commodityInfoService.selectList(wrapper);
            log.info("2--------------------查询商品结束------------------");
            if (isNull(listA)) {
                return;
            }
            for (CommodityInfoDTO dtoA : listA) {
                CommodityInfoDTO updateA = new CommodityInfoDTO();
                updateA.setId(dtoA.getId());
                updateA.setIsPushLook(1);
                commodityInfoService.updateById(updateA);
            }
        } else {
            Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id", shopId).andNew().eq("audit_status", 0).or().eq("audit_status", 2)
                    .andNew().eq("is_pass_look", 0);
            log.info("--------------------查询商品开始------------------");
            List<CommodityInfoDTO> listB = commodityInfoService.selectList(wrapper);
            log.info("--------------------查询商品结束------------------");
            if (isNull(listB)) {
                return;
            }
            for (CommodityInfoDTO dtoB : listB) {
                CommodityInfoDTO updateB = new CommodityInfoDTO();
                updateB.setId(dtoB.getId());
                updateB.setIsPassLook(1);
                commodityInfoService.updateById(updateB);
            }
        }
    }

    /**
     * @Description: 修改订单查看状态
     * @Author: chenyu.wang
     * @Params: [shopId, type:1买家，2卖家]
     * @Date: 2020.12.14 15:23
     */
    private void updateOrderLook(Long shopId, Integer type) {
        if (type == 1) {
            // 获取未查看的订单
            List<Long> ids = shopTipMapper.queryOrderLook(1, shopId);
            if (isNull(ids)) {
                return;
            }
            for (Long id : ids) {
                OrderStatusDTO updateA = new OrderStatusDTO();
                updateA.setId(id);
                updateA.setIsBuyerOrderLook(1);
                orderStatusService.updateById(updateA);
            }
        } else {
            // 获取未查看的订单
            List<Long> ids = shopTipMapper.queryOrderLook(2, shopId);
            if (isNull(ids)) {
                return;
            }
            for (Long id : ids) {
                OrderStatusDTO updateA = new OrderStatusDTO();
                updateA.setId(id);
                updateA.setIsSellerOrderLook(1);
                orderStatusService.updateById(updateA);
            }
        }
    }

    /**
     * @Description: 发票查看状态更改
     * @Author: chenyu.wang
     * @Params: [shopId, type]
     * @Date: 2020.12.14 15:47
     */
    private void updateInvoiceLook(Long shopId, Integer type) {
        if (type == 1) {
            // 获取未查看的订单
            List<Long> ids = shopTipMapper.queryInvoiceLook(1, shopId);
            if (isNull(ids)) {
                return;
            }
            for (Long id : ids) {
                OrderStatusDTO updateA = new OrderStatusDTO();
                updateA.setId(id);
                updateA.setIsInvoiceBuyerLook(1);
                orderStatusService.updateById(updateA);
            }
        } else {
            // 获取未查看的订单
            List<Long> ids = shopTipMapper.queryInvoiceLook(2, shopId);
            if (isNull(ids)) {
                return;
            }
            for (Long id : ids) {
                OrderStatusDTO updateA = new OrderStatusDTO();
                updateA.setId(id);
                updateA.setIsInvoiceSellerLook(1);
                orderStatusService.updateById(updateA);
            }
        }
    }

    /**
     * @Description: 废弃合同查看
     * @Author: chenyu.wang
     * @Params: [shopId, type]
     * @Date: 2020.12.14 15:48
     */
    private void updateContactLook(Long shopId, Integer type) {
        if (type == 1) {
            // 获取未查看的订单
            List<Long> ids = shopTipMapper.queryContactLook(1, shopId);
            if (isNull(ids)) {
                return;
            }
            for (Long id : ids) {
                OrderStatusDTO updateA = new OrderStatusDTO();
                updateA.setId(id);
                updateA.setIsBuyerContactLook(1);
                orderStatusService.updateById(updateA);
            }
        } else {
            // 获取未查看的订单
            List<Long> ids = shopTipMapper.queryContactLook(2, shopId);
            if (isNull(ids)) {
                return;
            }
            for (Long id : ids) {
                OrderStatusDTO updateA = new OrderStatusDTO();
                updateA.setId(id);
                updateA.setIsSellerContactLook(1);
                orderStatusService.updateById(updateA);
            }
        }
    }

}
